package com.qd.p2p.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.CooperationLoginService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.util.qq.OpenQqUtils;
import com.qdlc.p2p.biz.util.qq.QqGetUserInfoParamBean;
import com.qdlc.p2p.biz.util.qq.QqGetUserInfoResultBean;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.CooperationLoginType;
import com.qdlc.p2p.dal.dto.CooperationLogin;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.UserModel;


public class CooperationQQLoginAction extends BaseAction<User> implements ModelDriven<User>{

	private Map<String, Object> data;
	
	private User user = new User();

	@Override
	public User getModel() {
		return user;
	}
	
	@Resource
	private CooperationLoginService cooperationLoginService;
	@Resource
	private UserService userService;
	
	// 日志
    protected final Logger    log = Logger.getLogger(this.getClass());
	
    @Action("/user/qqLogin")
	public void qqLogin(){
		// QQ互联工具类 
		OpenQqUtils oqu = new OpenQqUtils();
		try {
			request.setAttribute("qqLoginUrl", oqu.getQqLoginUrl());
			response.sendRedirect(oqu.getQqLoginUrl());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    @Action("/user/doQQLogin")
	public String loginSuccess()throws IOException {
		// QQ互联工具类 
		OpenQqUtils oqu = new OpenQqUtils();
		// 动态拼接换取accessToken的URL 
		String accessTokenUrl = oqu.getAccessTokenUrl(request.getParameter("code"));
		// AccessToken
		String accessToken = oqu.getAccessToken(accessTokenUrl);
		// OpenId
		String openId = oqu.getOpenId(accessToken);
		
		if(openId == null || openId.length() <= 0  || accessToken == null || accessToken.length() <= 0){
			return "login";
		}
		QqGetUserInfoParamBean paramBean = new QqGetUserInfoParamBean();
		paramBean.setAccessToken(accessToken);
		paramBean.setOpenId(openId);
		QqGetUserInfoResultBean userInfoResultBean = oqu.getUserInfo(paramBean);
		// 判断qq合作登录的接口 获取合作登录会员基本信息失败操作
		if (userInfoResultBean.getErrorFlg()) {
			this.log.error("QQ合作登录_QQ登录信息验证失败 ");
			return "login";
		}
		String getNickname = userInfoResultBean.getNickName();
		if(getNickname != null && getNickname.length() > 0){
			request.setAttribute("nickname", getNickname);
		}
		
		// 封装联合登录信息
		CooperationLogin cooperation = new CooperationLogin();
		cooperation.setOpenId(openId);
		cooperation.setOpenKey(accessToken);
		cooperation.setType(Integer.parseInt(CooperationLoginType.TYPE_QQ));
		cooperationLoginService.addCooperationLogin(cooperation);
		
		CooperationLogin qqLogin = cooperationLoginService.getCooperationLogin(openId, Integer.parseInt(CooperationLoginType.TYPE_QQ));
		// 如果查询联合登录信息不为空，并且user_id不为空，则说明QQ已被绑定，查询user信息，跳转至登录的action
		if(qqLogin != null && qqLogin.getUserId() > 0){
			User user = userService.find(qqLogin.getUserId());
			request.setAttribute("openUser", user);
			try {
				request.getRequestDispatcher("/user/doLogin.html").forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			}
		}else if(qqLogin != null && qqLogin.getId() > 0 && qqLogin.getUserId() <= 0){// 如果查询联合登录信息不为空，并且user_id为空，则说明QQ未被绑定，跳转至登录的注册页面
			request.setAttribute("openId", qqLogin.getOpenId());
			request.setAttribute("openType", CooperationLoginType.TYPE_QQ);
			return "qqRegister";
		}
		return "login";
	}
    
    /**
	 * 进行用户注册
	 * 
	 * @return 
	 * @throws Exception
	 */
	@Action("/user/doQQRegister")
	public String doQQRegister() throws Exception {
		data = new HashMap<String, Object>();
		String openType = this.paramString("openType");
		String openId = this.paramString("openId");
		if(openType == null || openType.length() <= 0 || openId == null || 
				openId.length() <= 0 || !openType.equals(CooperationLoginType.TYPE_QQ)){// 判断数据类型是否正确
			data.put("result", false);
			data.put("msg", "注册失败！");
			return null;
		}
		UserModel userModel = UserModel.instance(user);
		userModel.setValidCode(paramString("validCode"));
		userModel.validRegRule();
		userModel.validRegModel();
		User u = cooperationLoginService.doQQRegister(userModel.prototype(),openType,openId);
		if (u != null) {
			data.put("result", true);
			data.put("msg", "注册成功！");
			data.put("userId", u.getUserId());
			data.put("userName", u.getUserName());
			data.put("email", u.getEmail());
			printWebJson(getStringOfJpaObj(data));
		} else {
			data.put("result", false);
			data.put("msg", "注册失败！");
		}
		return null;
	}
}
